/**
 * 彩伞JavaScript工具包
 * @author 谢小旭
 */
$.extend({
    /**
     * 数组序列化
     * v:[1,2,3] f:id => id=1&id=2&id=3 
     * 备注：$.ajax提交可以用[].join(',')代替
     */
    arrayToSerial : function(values, field){
        var r = '', field = field || 'id';
        if(values && values.length>0){
            var d = [];
            $(values).each(function(i, v){
                d.push(field + '=' + v);
            });
            r = d.join('&');
        }
        return r;
    },
    
    /**
     * 对象序列化
     * {id:1, name:2, c:[1,2]} => id=1&name=2&c=1&c=2
     */
    objectToSerial : function(obj){
        var data = [];
        for ( var p in obj) {
            if(obj[p] instanceof Array){
                $(obj[p]).each(function(i, v){
                    data.push(p + '=' + v);
                });
            } else {
                data.push(p + '=' + obj[p]);
            }
        }
        return data.join('&');
    },
    
    /**
     * 将from序列化参数转Object
     * id=1&name=1&a=1&a=2 => {id:1, name:2, a:[1,2]}
     * 备注：key为多个的会转化为数组
     */
    paramsToObject : function(params){
        if(params){
            params = params.replaceAll('\\+', ' ');
            params = decodeURIComponent(params);
        }
        var obj = {};
        var param = params.split("&");
        var keys = [];
        for (var i = 0; param != null && i < param.length; i++) {
            var para = param[i].split("=");
            if(!$.contains(keys, para[0])){//keys.contains(para[0])
                keys.push(para[0]);
            }
        }
        for ( var i = 0; keys != null && i < keys.length; i++) {
            var value = [];
            for (var j = 0; param != null && j < param.length; j++) {
                var para = param[j].split("=");
                if(keys[i] == para[0]){
                    value.push(para[1].trim());
                }
            }
            if(value.length == 1){
                value = value[0];
            }
            obj[keys[i]] = value;
        }
        return obj;
    },
    
    /**
     * 简化数组的Object
     * {id:1, name:2, a:[1,2]} => {id:1, name:2, a:'1,2'}
     */
    simpleArrayObject : function(obj){
        for ( var p in obj) {
            if(obj[p] instanceof Array){
                obj[p] = obj[p].join(',');
            }
        }
        return obj;
    },
    
    /**
     * form参数转Object
     * id=1&name=1&a=1&a=2 => {id:1, name:2, a:'1,2'}
     * 备注：主要用于$.ajax提交
     */
    formParamsToObject : function(params){
        var obj = this.paramsToObject(params);
        return this.simpleArrayObject(obj);
    },
    
    /**
     * 将pid转换为children的树形结构
     */
    pidToChildren : function(datas, pid){
        if(!pid) pid = null;
        var list = [];
        $(datas).each(function(i, item){
            if(item.pid == pid){
                var children = [];
                $(datas).each(function(j, data){
                    if(item.id == data.pid){
                        children.push(data);
                    }
                });
                if(children.length > 0){
                    item.children = children;
                }
                list.push(item);
                $.pidToChildren(datas, item.id);
            }
        });
        return list;
    },
    
    /**
     * 生成随机字符串
     */
    generateRandomString: function(n){
        var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
         var res = "";
         for(var i = 0; i < n ; i ++) {
             var id = Math.ceil(Math.random()*35);
             res += chars[id];
         }
         return res;
    },
    
    datatableSelectAllTitle: function(){
    	return '<div class="checkbox checkbox-primary"><input id="datatableSelectAllTitle" type="checkbox"><label for="datatableSelectAllTitle"> </label></div>';
    },
    
    datatableSelectAllRow: function(data){
    	var $div = $('<div class="checkbox checkbox-primary">');
    	$div.append($('<input id="table-checkbox-'+data+'" name="selectAll" type="checkbox">').val(data));
    	$div.append($('<label for="table-checkbox-'+data+'">').text(' '));
        return $div[0].outerHTML;
    },
    
    dataFinal: function(key, value){
    	var text = '';
    	$('select[data-final="'+key+'"]').find('option').each(function(i, row){
    		if($(this).val() == value){
    			text = $(this).text();
    			return false;
    		}
    	});
    	return text;
    }
});
$.fn.extend({
    /**
     * 根据对象数据填充表单
     */
    fillin : function(obj){
        var key, value, tagName, type, arr;
        for (x in obj) {
            key = x;
            value = obj[x];
            $("[name='" + key + "'],[name='" + key + "[]']", $(this)).each(function() {
                tagName = $(this)[0].tagName;
                type = $(this).attr('type');
                if (tagName == 'INPUT') {
                    if (type == 'radio') {
                        $(this).prop('checked', $(this).val() == value);
                    } else if (type == 'checkbox') {
                        arr = value.split(',');
                        for (var i = 0; i < arr.length; i++) {
                            if ($(this).val() == arr[i]) {
                                $(this).prop('checked', true);
                                break;
                            }
                        }
                    } else {
                        $(this).val(value);
                    }
                } else if (tagName == 'SELECT' || tagName == 'TEXTAREA') {
                    $(this).val(value);
                }
            });
        }
    },
    
    /**
     * 清空表单的值
     */
    fillout : function(){
        var $form  = $(this);
        $form[0].reset();
        $('input[type=hidden]', $form).val('');
    },
    
    /**
     * datatable获取全选数据
     */
    getSelectAllData: function(){
    	var ids = [];
    	$('input[name="selectAll"]:checked', $(this)).each(function(i, row){
    		ids.push($(this).val());
    	});
    	return ids;
    }
    
});

$(function(){
	$('body').on('click', '#datatableSelectAllTitle' ,function(){
		var isCheck = $(this).prop('checked');
		if(isCheck) {
			$('input[name="selectAll"]', $(this).closest('.dataTables_wrapper')).prop('checked', true);
		} else {
			$('input[name="selectAll"]', $(this).closest('.dataTables_wrapper')).prop('checked', false);
		}
	});
});
